package com.jintoufs.service.org.impl;

import com.google.common.collect.Maps;
import com.jintoufs.dao.org.OrgDAO;
import com.jintoufs.domain.org.Org;
import com.jintoufs.service.org.OrgService;
import com.jintoufs.util.ztree.TreeNode;
import org.cosmos.modules.web.msg.AjaxMsg;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service(value = "orgService")
public class OrgServiceImpl implements OrgService {

    @Resource
    private OrgDAO orgDAO;

    @Override
    public Org add(Org org, AjaxMsg ajaxMsg) {
        if (org != null) {
            Map<String, Object> params = Maps.newHashMap();
            params.put("name", org.getOrgName());
            if (orgDAO.getCountByParams(params) > 0) {
                ajaxMsg.setCode(AjaxMsg.FAILURE);
                ajaxMsg.setMessage("名称已经存在！");
                return org;
            }
            params = Maps.newHashMap();
            params.put("code", org.getOrgCode());
            if (orgDAO.getCountByParams(params) > 0) {
                ajaxMsg.setCode(AjaxMsg.FAILURE);
                ajaxMsg.setMessage("编号已经存在！");
                return org;
            }
        }
        orgDAO.insert(org);
        return org;
    }

    @Override
    public void update(Org org, AjaxMsg ajaxMsg) {
        Org entity = orgDAO.getById(org.getId());
        Map<String, Object> params = Maps.newHashMap();
        if (org.getOrgName() != null && !org.getOrgName().equals(entity.getOrgName())) {
            params.put("name", org.getOrgName());
            if (orgDAO.getCountByParams(params) > 0) {
                ajaxMsg.setCode(AjaxMsg.FAILURE);
                ajaxMsg.setMessage("名称已经存在！");
                return;
            }
        } else if (org.getOrgCode() != null && !org.getOrgCode().equals(entity.getOrgCode())) {
            params.put("code", org.getOrgCode());
            if (orgDAO.getCountByParams(params) > 0) {
                ajaxMsg.setCode(AjaxMsg.FAILURE);
                ajaxMsg.setMessage("编号已经存在！");
                return;
            }
        }
        orgDAO.update(org);
    }

    /**
     * 根据区域信息构建树节点 <br />
     * 区域信息代表的树节点原则上都是父节点,但可以没有子节点
     *
     * @param org
     * @param oldOrg
     * @return
     */
    private TreeNode buildNode4Org(Org org, Org oldOrg, boolean ifParentCheck) {
        TreeNode areaNode = new TreeNode();
        areaNode.setId(String.valueOf(org.getId()));
        areaNode.setName(org.getOrgName());
        if (org.getParentId() != null && org.getParentId() != 0) {
            areaNode.setPId(String.valueOf(org.getParentId()));
        } else {
            areaNode.setIsParent(true); // 处理无子节点的父节点
        }
        if (ifParentCheck) {
            if (oldOrg != null && oldOrg.getParentId() == org.getId()) {
                areaNode.setChecked(true);
            }
        } else {
            if (oldOrg != null && oldOrg.getId() == org.getId()) {
                areaNode.setChecked(true);
            }
        }
        areaNode.setOpen(false);
        return areaNode;
    }

    /**
     * 根据客户编码取得机构树
     *
     * @param entity
     */
    @Override
    public List<TreeNode> getOrgMenu(Org entity, int level, boolean ifParentCheck) {
        List<Org> list = orgDAO.getByFilter(null);
        List<TreeNode> nodes = new ArrayList<TreeNode>();
        /* 根据网点OID构建数据时,只需要两级即可(网点及其直接上级区域) */
        int num = 0;
        for (Org tmp : list) {
            num = getStringIndexOfNumber(tmp.getParentIds(), "/");
            if (num <= level) {
                nodes.add(buildNode4Org(tmp, entity, ifParentCheck));
            }
        }
        return nodes;
    }

    /**
     * 判断字符串包含某个字符的个数
     *
     * @param str1
     * @param str2
     * @return
     */
    private int getStringIndexOfNumber(String str1, String str2) {
        int counter = 0;
        if (str1.indexOf(str2) == -1) {
            return 0;
        }
        while (str1.indexOf(str2) != -1) {
            counter++;
            str1 = str1.substring(str1.indexOf(str2) + str2.length());
        }
        return counter;
    }

    @Override
    public List<Org> queryByParams(Map<String, Object> params) {
        return orgDAO.getByFilter(params);
    }

    @Override
    public Org getById(int id) {
        return orgDAO.getById(id);
    }

    @Override
    public void deleteById(Integer id, AjaxMsg ajaxMsg) {
        if (orgDAO.isUsedByUser(id)) {
            ajaxMsg.setCode(AjaxMsg.FAILURE);
            ajaxMsg.setMessage("该机构已经分配了用户，无法删除！");
            return;
        }
        orgDAO.deleteById(id);
    }
}
